<script setup>
import { ref, onMounted, computed } from 'vue'
import PageContainer from '@/components/pageContainer.vue'
import {
  getPropertyDetailService,
  publishPropertyService
} from '@/apis/property'
import { pcaTextArr } from 'element-china-area-data'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
const UserStore = useUserStore()

// 获取表单进行校验
const formRef = ref(null)

const formModel = ref({
  title: '',
  description: '',
  address: '',
  resident: '',
  province: '',
  city: '',
  county: '',
  longitude: '',
  latitude: '',
  room_count: '',
  livingroom_count: '',
  bathroom_count: '',
  room_area: '',
  price: '',
  room_type: '',
  decorate_type: '',
  rent_type: '',
  floor: '',
  room_direction: '',
  bedroom_facility: {
    tv: false,
    bed: false,
    closet: false,
    balcony: false,
    heating: false,
    bathroom: false,
    smart_lock: false,
    air_conditioner: false
  },
  public_facility: {
    sofa: false,
    fridge: false,
    broadband: false,
    gas_stove: false,
    range_hood: false,
    water_heater: false,
    cooking_allowed: false,
    washing_machine: false
  },
  image_url: {
    interior_img: '',
    floor_plan_img: ''
  }
})

const rules = {
  title: {
    required: true,
    message: '请输入房源标题',
    trigger: 'blur'
  },
  description: {
    required: true,
    message: '请输入房源描述',
    trigger: 'blur'
  },
  address: {
    required: true,
    message: '请输入地址',
    trigger: 'blur'
  },
  resident: {
    required: true,
    message: '请输入小区',
    trigger: 'blur'
  },
  longitude: {
    required: true,
    message: '请输入经度',
    trigger: 'blur'
  },
  latitude: {
    required: true,
    message: '请输入纬度',
    trigger: 'blur'
  },
  room_count: {
    required: true,
    message: '请输入房间数量',
    trigger: 'blur'
  },
  livingroom_count: {
    required: true,
    message: '请输入客厅数量',
    trigger: 'blur'
  },
  bathroom_count: {
    required: true,
    message: '请输入卫生间数量',
    trigger: 'blur'
  },
  room_area: {
    required: true,
    message: '请输入面积',
    trigger: 'blur'
  },
  price: {
    required: true,
    message: '请输入价格',
    trigger: 'blur'
  },
  room_type: {
    required: true,
    message: '请选择房源类型',
    trigger: 'blur'
  },
  decorate_type: {
    required: true,
    message: '请选择装修类型',
    trigger: 'blur'
  },
  rent_type: {
    required: true,
    message: '请选择租赁类型',
    trigger: 'blur'
  },
  floor: {
    required: true,
    message: '请输入楼层',
    trigger: 'blur'
  },
  room_direction: {
    required: true,
    message: '请选择朝向',
    trigger: 'blur'
  }
}

// 存储室内图列表
const interiorList = ref([])
// 存储户型图列表
const floorList = ref([])

// 省市县数据
const options = ref(pcaTextArr)

// 当前选择的省市县数据
const selectedOption = ref([])

// 映射卧室设施键名到显示文本
const displayBedroomFacility = computed(() => ({
  tv: '电视',
  bed: '床',
  closet: '衣柜',
  balcony: '阳台',
  heating: '暖气',
  bathroom: '卫生间',
  smart_lock: '智能门锁',
  air_conditioner: '空调'
}))

// 映射公共设施键名到显示文本
const displayPublicFacility = computed(() => ({
  sofa: '沙发',
  fridge: '冰箱',
  broadband: '宽带',
  gas_stove: '燃气灶',
  range_hood: '油烟机',
  water_heater: '热水器',
  cooking_allowed: '可做饭',
  washing_machine: '洗衣机'
}))

// 页面初始化时接收其他页面传递过来的房源ID，向后后端发请求填充表格，如果没有ID插入不执行操作
onMounted(async () => {
  const id = route.query.id
  if (id) {
    const res = await getPropertyDetailService(id)
    // 将房源相关数据存储在formModel里面
    formModel.value = res.data.data

    // 处理室内图在图片墙中显示
    interiorList.value = res.data.data?.image_url?.interior_img.map((item) => {
      return {
        name: item.type,
        url: item.url
      }
    })

    // 处理户型图在图片墙中显示
    floorList.value = [
      {
        name: 'floor_plan_img',
        url: res.data.data?.image_url?.floor_plan_img.url
      }
    ]

    // 自动选择省市县
    selectedOption.value = [
      `${formModel.value.province}`,
      `${formModel.value.city}`,
      `${formModel.value.county}`
    ]
  }
})

// 处理房源图片相关功能

// 需要预览的图片的地址
const dialogImageUrl = ref('')

// 控制图片预览的显示与隐藏
const dialogVisible = ref(false)

// 预览图片
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

// 删除预览的图片
const handleRemove = (file, fileList) => {
  // 从fileList里删除文件
  const index = fileList.indexOf(file)
  if (index !== -1) {
    fileList.splice(index, 1)
  }
}

// 图片上传前添加请求头
const token = computed(() => UserStore.UserList.token)
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${token.value}`
}))

// 图片上传前的操作
const beforeUpload = () => {
  if (!token.value) {
    ElMessage.error('请先登录或获取token')
    return false
  }
  return true
}

// 图片上传成功时的操作
const handleSuccess = (response, UploadFile, UploadFiles) => {
  if (response.type === 'interior') {
    // 将室内图存储到formModel里
    formModel.value.image_url.interior_img = UploadFiles.filter((item) => {
      return item.response.type === 'interior'
    }).map((item) => {
      return {
        type: item.response.type,
        uid: item.uid,
        url: item.response.url
      }
    })
  } else {
    // 将户型图存储到formModel里
    const floorItem = UploadFiles.find((item) => {
      return item.response.type === 'floor'
    })
    formModel.value.image_url.floor_plan_img = {
      type: floorItem.response.type,
      uid: floorItem.uid,
      url: floorItem.response.url
    }
  }
  ElMessage.success('图片上传成功')
}

// 图片上传失败时的操作
const handleError = (error) => {
  ElMessage.error('图片上传失败', error.message)
}

// 处理省市县选择变化的情况
const handleRegionChange = (value) => {
  selectedOption.value = value
  formModel.value.province = selectedOption.value[0]
  formModel.value.city = selectedOption.value[1]
  formModel.value.county = selectedOption.value[2]
}

// 发布房源
const publishProperty = async () => {
  await formRef.value.validate()

  // 添加管理员ID
  formModel.value.admin_id = UserStore.UserList.id
  // 发布房源信息
  await publishPropertyService(formModel.value)
  ElMessage.success('发布房源成功')
  router.push('/property/list')
}
</script>

<template>
  <pageContainer title="发布房源">
    <el-form
      class="form"
      autocomplete="off"
      label-width="120"
      size="large"
      :model="formModel"
      :rules="rules"
      ref="formRef"
    >
      <el-row :gutter="20" justify="space-around">
        <el-col :span="10">
          <el-form-item label="房源标题" prop="title">
            <el-input
              v-model="formModel.title"
              placeholder="请输入房源标题"
            ></el-input>
          </el-form-item>

          <el-form-item label="房源描述" prop="description">
            <el-input
              v-model="formModel.description"
              placeholder="请输入房源描述"
            ></el-input>
          </el-form-item>

          <el-form-item label="地址" prop="address">
            <el-input
              v-model="formModel.address"
              placeholder="请输入地址"
            ></el-input>
          </el-form-item>

          <el-form-item label="小区" prop="resident">
            <el-input
              v-model="formModel.resident"
              placeholder="请输入小区"
            ></el-input>
          </el-form-item>

          <el-form-item label="价格" prop="price">
            <el-input
              v-model="formModel.price"
              placeholder="请输入价格"
            ></el-input>
          </el-form-item>

          <el-form-item label="省市县">
            <el-cascader
              v-model="selectedOption"
              :options="options"
              clearable
              placeholder="请选择省市县"
              @change="handleRegionChange"
            ></el-cascader>
          </el-form-item>

          <el-form-item label="房源类型" prop="room_type">
            <el-select
              v-model="formModel.room_type"
              placeholder="请选择房源类型"
              style="width: 240px"
            >
              <el-option label="公寓" value="公寓" />
              <el-option label="别墅" value="别墅" />
              <el-option label="学区房" value="学区房" />
              <el-option label="民宿" value="民宿" />
            </el-select>
          </el-form-item>

          <el-form-item label="装修类型" prop="decorate_type">
            <el-select
              v-model="formModel.decorate_type"
              placeholder="请选择装修类型"
              style="width: 240px"
            >
              <el-option label="基础装修" value="基础装修" />
              <el-option label="精装修" value="精装修" />
              <el-option label="局部改造" value="局部改造" />
            </el-select>
          </el-form-item>

          <el-form-item label="租赁类型" prop="rent_type">
            <el-select
              v-model="formModel.rent_type"
              placeholder="请选择租赁类型"
              style="width: 240px"
            >
              <el-option label="整租" value="整租" />
              <el-option label="合租" value="合租" />
              <el-option label="长租" value="长租" />
              <el-option label="短租" value="短租" />
            </el-select>
          </el-form-item>

          <el-form-item label="朝向" prop="room_direction">
            <el-select
              v-model="formModel.room_direction"
              placeholder="请选择朝向"
              style="width: 240px"
            >
              <el-option label="东" value="东" />
              <el-option label="南" value="南" />
              <el-option label="西" value="西" />
              <el-option label="北" value="北" />
              <el-option label="东北" value="东北" />
              <el-option label="西北" value="西北" />
              <el-option label="东南" value="东南" />
              <el-option label="西南" value="西南" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="10">
          <el-form-item label="经度" prop="longitude">
            <el-input
              v-model="formModel.longitude"
              placeholder="请输入经度"
            ></el-input>
          </el-form-item>

          <el-form-item label="纬度" prop="latitude">
            <el-input
              v-model="formModel.latitude"
              placeholder="请输入纬度"
            ></el-input>
          </el-form-item>

          <el-form-item label="房间数量" prop="room_count">
            <el-input
              v-model="formModel.room_count"
              placeholder="请输入房间数量"
            ></el-input>
          </el-form-item>

          <el-form-item label="客厅数量" prop="livingroom_count">
            <el-input
              v-model="formModel.livingroom_count"
              placeholder="请输入客厅数量"
            ></el-input>
          </el-form-item>

          <el-form-item label="卫生间数量" prop="bathroom_count">
            <el-input
              v-model="formModel.bathroom_count"
              placeholder="请输入卫生间数量"
            ></el-input>
          </el-form-item>

          <el-form-item label="面积" prop="room_area">
            <el-input
              v-model="formModel.room_area"
              placeholder="请输入面积"
            ></el-input>
          </el-form-item>

          <el-form-item label="楼层" prop="floor">
            <el-input
              v-model="formModel.floor"
              placeholder="请输入楼层"
            ></el-input>
          </el-form-item>

          <el-form-item label="卧室设施">
            <el-checkbox
              v-for="(label, key) in displayBedroomFacility"
              :key="key"
              :label="key"
              v-model="formModel.bedroom_facility[key]"
            >
              {{ label }}
            </el-checkbox>
          </el-form-item>

          <el-form-item label="公共设施">
            <el-checkbox
              v-for="(label, key) in displayPublicFacility"
              :key="key"
              :label="key"
              v-model="formModel.public_facility[key]"
            >
              {{ label }}
            </el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" justify="space-around" style="margin-top: 20px">
        <el-col :span="10">
          <el-form-item label="室内图">
            <!-- 图片上传 -->
            <el-upload
              v-model:file-list="interiorList"
              action="http://127.0.0.1:3000/api/property/upload?type=interior"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
              :headers="uploadHeaders"
              :on-success="handleSuccess"
              :on-error="handleError"
              multiple="true"
            >
              <el-icon><i-ep-Plus></i-ep-Plus></el-icon>
            </el-upload>

            <!-- 图片预览 -->
            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>
        </el-col>
        <el-col :span="10" justify="center">
          <el-form-item label="户型图">
            <!-- 图片上传 -->
            <el-upload
              v-model:file-list="floorList"
              action="http://127.0.0.1:3000/api/property/upload?type=floor"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
              :headers="uploadHeaders"
              :on-success="handleSuccess"
              :on-error="handleError"
              :limit="1"
            >
              <el-icon><i-ep-Plus></i-ep-Plus></el-icon>
            </el-upload>

            <!-- 图片预览 -->
            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :offset="15" style="margin-bottom: 100px">
          <el-button type="primary" size="large" @click="publishProperty">
            <template #icon>
              <el-icon>
                <i-ep-Position></i-ep-Position>
              </el-icon>
            </template>
            <template #default>发布</template>
          </el-button>
        </el-col>
      </el-row>
    </el-form>
  </pageContainer>
</template>

<style lang="scss" scoped>
.image-item {
  width: 100px;
  height: 100px;
  display: inline-block;
  margin-right: 10px;
}
</style>
